package com.example.pt.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.pt.entity.UserSeedStats;
import com.example.pt.service.UserSeedStatsService;
import com.example.pt.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户保种统计控制器
 */
@RestController
@RequestMapping("/api/user/seed-stats")
@CrossOrigin(origins = "*")
public class UserSeedStatsController {

    @Autowired
    private UserSeedStatsService userSeedStatsService;

    /**
     * 获取用户的保种统计列表
     * @return 保种统计列表
     */
    @GetMapping
    public ResponseEntity<?> getUserSeedStats(@RequestHeader Map<String, String> headers) {
        String token = headers.get("token");
        if (token == null) {
            token = headers.get("authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
        }
        
        if (token == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "未登录: 缺少token");
            response.put("status", "error");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
        
        try {
            DecodedJWT jwt = JWTUtil.verifyToken(token);
            Integer userId = jwt.getClaim("uid").asInt();
            
            List<UserSeedStats> statsList = userSeedStatsService.getUserSeedStatsList(userId);
            int totalPoints = userSeedStatsService.getTotalSeedPoints(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("userId", userId);
            response.put("totalSeedPoints", totalPoints);
            response.put("seedStats", statsList);
            response.put("status", "success");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "未登录: " + e.getMessage());
            response.put("status", "error");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }

    /**
     * 手动更新所有用户的保种统计
     * 仅管理员可用
     * @return 更新结果
     */
    @PostMapping("/update-all")
    public ResponseEntity<?> updateAllUserSeedStats() {
        try {
            userSeedStatsService.updateAllUserSeedStats();
            return ResponseEntity.ok("所有用户的保种统计数据已更新");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("更新保种统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户的总保种积分
     * @return 总保种积分
     */
    @GetMapping("/points")
    public ResponseEntity<?> getUserSeedPoints(@RequestHeader Map<String, String> headers) {
        String token = headers.get("token");
        if (token == null) {
            token = headers.get("authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
        }
        
        if (token == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "未登录: 缺少token");
            response.put("status", "error");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
        
        try {
            DecodedJWT jwt = JWTUtil.verifyToken(token);
            Integer userId = jwt.getClaim("uid").asInt();
            
            // 直接获取最新的保种积分，不单独调用更新方法
            // 因为UserSeedStatsService中的updateUserSeedStats方法需要infoHash参数
            int points = userSeedStatsService.getTotalSeedPoints(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("userId", userId);
            response.put("seedPoints", points);
            response.put("status", "success");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "未登录: " + e.getMessage());
            response.put("status", "error");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }
} 